package com.community.service.impl;

import com.community.annotation.SysLog;
import com.community.base.BaseService;
import com.community.common.Const;
import com.community.common.ServerResponse;
import com.community.pojo.*;
import com.community.service.IAnswerService;
import com.community.service.IIntegralService;
import com.community.service.IRemindService;
import com.community.service.ISolrService;
import com.community.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * 回答服务层
 */
@Service("iAnswerService")
public class AnswerServiceImpl extends BaseService implements IAnswerService {


    @Autowired
    private ISolrService iSolrService;

    @Autowired
    private IRemindService iRemindService;

    @Autowired
    private IIntegralService iIntegralService;

    /**
     * 查询优质回答(首页推荐)
     * @return
     */
    @SysLog("查询回答")
    public ServerResponse<PageInfo> selectGreatAnswer(int pageNum,String order,HttpServletRequest request){
        //查询高赞/高评论回答
        PageHelper.startPage(pageNum, Const.MAXSIZE,order);
        //查询
        Map map = new HashMap();
        map.put("show",Const.YesOrNo.YES);
        List<Map> resultList = answerMapper.selectGreatAnswer(map);
        if(null != resultList && 0 < resultList.size()){
            PageInfo pageInfo = new PageInfo(resultList);
            //查询大字段
            return SearchBigFieldUtil.selectBigText(pageInfo,Answer.ENTITYNAME,
                    Const.SolrType.CONTENT,request);
        }
        return ServerResponse.createBySuccessMessage(Const.Msg.SELECTSUCCESS);
    }

    /**
     * 添加/更新回答
     * @param paramMap
     * @param request
     * @return
     */
    @Transactional(rollbackFor = { Exception.class })//事物控制
    @SysLog("添加回答")
    public ServerResponse<String> addOrUpdate(Map paramMap,HttpServletRequest request) {
        String userName = StringUtil.valueOfString(paramMap.get("userName"));
        if (!LoginUtil.isLogin(request, userName)) {
            return ServerResponse.createByErrorMessage(Const.Msg.PARAMTERERROR);
        }
        int qid = NumberUtil.safeToNumber(paramMap.get("qid"));
        /**
         * 更新问题状态
         */
        //查询问题状态
        Question question = questionMapper.selectByPrimaryKey(qid);
        if (null == question) {
            return ServerResponse.createByErrorMessage(Const.Msg.PARAMTERERROR);
        }
        //如果是等待解答状态才更新为等待处理
        if (Const.QuestStatus.WAITANSWER == question.getStatus()) {
            question.setStatus(Const.QuestStatus.WQITHANDLE);
            if (questionMapper.updateByPrimaryKeySelective(question) <= 0) {
                return ServerResponse.createByErrorMessage(Const.Msg.SAVEERROR);
            }
        }
        /**
         * 新增/修改回答
         */
        int id = NumberUtil.safeToNumber(paramMap.get("id"));//回答ID
        Answer answer = null;
        if (id > 0) {
            answer = answerMapper.selectByPrimaryKey(id);
        }
        if (null == answer) {
            answer = new Answer();
        }
        answer.setQid(qid);//提问ID
        answer.setCommentmode(NumberUtil.safeToNumber(paramMap.get("commentmode")));//评论模式（1:允许所有人评论,2:评论筛选后显示,3:允许我关注的人评论,4:关闭评论）
        answer.setAnonymous(NumberUtil.safeToNumber(paramMap.get("anonymous")));//是否匿名（1:是,2:否）
        answer.setReprint(NumberUtil.safeToNumber(paramMap.get("reprint")));//'转载方式（1:允许规范转载,2:允许付费转载,3:禁止转载）',
        answer.setIp(ToolUtil.getClientIp(request));//评论IP
        answer.setShow(NumberUtil.safeToNumber(paramMap.get("show")));//是否展示
        answer.setUsername(userName);//评论用户名
        answer.setAdopt(Const.YesOrNo.NO);//是否被采纳
        answer.setAnswerModel(NumberUtil.safeToNumber(paramMap.get("answerModel")));//答案可见模式
        answer.setAnswerMoney(NumberUtil.safeToDouble(paramMap.get("answerMoney")));//付费金额
        if (id > 0) {
            //如果是更新
            answerMapper.updateByPrimaryKeySelective(answer);
        } else{
            if(answerMapper.insert(answer) <= 0) {
                throw new RuntimeException();
            }
        }
        //保存大字段至数据库
        AnswerBigField answerBigField = null;
        if(id > 0){
            //更新状态下先查询是否有大字段内容
            answerBigField = answerBigFieldMapper.selectByAnswerId(answer.getId());
        }else{
            answerBigField = new AnswerBigField();
        }
        answerBigField.setAid(answer.getId());//回答ID
        answerBigField.setBigtext(StringUtil.valueOfString(paramMap.get("content")));//内容
        if(answerBigFieldMapper.insert(answerBigField) <= 0){
            throw new RuntimeException();
        }
        if(id > 0){
            //更新情况下先删除大字段
            iSolrService.del("joinid:"+answer.getId()+" AND entityName:"+Answer.ENTITYNAME+
                    " AND type:"+Const.SolrType.CONTENT);//删除索引
        }
        //添加大字段至服务器
        SolrInputDocument doc = new SolrInputDocument();
        doc.addField("id",UUID.randomUUID());
        doc.addField("joinid",answer.getId());
        doc.addField("entityName",Answer.ENTITYNAME);//实体名称
        doc.addField("type",Const.SolrType.CONTENT);//实体类型
        doc.addField("bigfield",StringUtil.valueOfString(paramMap.get("content")));//大字段内容
        try {
            iSolrService.add(doc);//添加至solr服务器
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        //添加事件
        iRemindService.addRemind(question.getProposeUser(),
                Const.MessageType.REMIND,
                Const.EventType.THREE,
                userName,
                Const.RemindTarget.ONE,
                question.getId());
        return ServerResponse.createBySuccessMessage(Const.Msg.SAVESUCCESS);
    }

    /**
     * 设置回答为显示/不显示
     * @param id
     * @param request
     * @return
     */
    public ServerResponse<String> updateShowStatusById(int id,int show,HttpServletRequest request){
        Answer answer = answerMapper.selectByPrimaryKey(id);
        if(null == answer){
            return ServerResponse.createByErrorMessage(Const.Msg.PARAMTERERROR);
        }
        if(!LoginUtil.isLogin(request,answer.getUsername())){
            return ServerResponse.createByErrorMessage(Const.Msg.PARAMTERERROR);
        }
        answer.setShow(show);
        if(answerMapper.updateByPrimaryKeySelective(answer) > 0){
            return ServerResponse.createBySuccessMessage(Const.Msg.SAVESUCCESS);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.SAVEERROR);
    }

    /**
     * 查看收费内容
     * @return
     */
    @Transactional(rollbackFor = { Exception.class })//事物控制
    @SysLog("查看收费内容")
    public ServerResponse<String> viewCharges(int answerId,HttpServletRequest request){
        //获取登录用户
        Object o = request.getSession().getAttribute(Const.CURRENT_USER);
        if(o == null){
            return ServerResponse.createByErrorMessage(Const.Msg.USERNOLOGIN);
        }
        User user = (User)o;
        Answer answer = answerMapper.selectByPrimaryKey(answerId);
        //返回内容
        SolrDocumentList list = SearchBigFieldUtil.getByIdAndEntityNameAndType(answerId,
                Answer.ENTITYNAME,Const.SolrType.CONTENT);
        String content = "";
        if(null != list && 0 < list.size()){
            content = StringUtil.valueOfString(list.get(0).getFieldValue("bigfield"));
        }
        if(user.getUsername().equals(answer.getUsername())){//自己查看自己的
            return ServerResponse.createBySuccess(Const.Msg.SELECTSUCCESS,content);
        }
        if(answer.getAnswerModel() != Const.AnswerModel.PAY){
            return ServerResponse.createBySuccess(Const.Msg.SELECTSUCCESS,content);
        }
        //查询用户是否已支付过
        if(answerPayRecordMapper.countByUserNameAndAnswerId(user.getUsername(),answerId) > 0){
            return ServerResponse.createBySuccess(Const.Msg.SELECTSUCCESS,content);
        }
        //查询用户积分是否充足
        Integer money = integralMapper.selectSurplusByUserName(user.getUsername());
        if(money < answer.getAnswerMoney()){
            return ServerResponse.createByErrorMessage(Const.Msg.DEFICIENCY);
        }
        //扣除用户积分
        ServerResponse response = iIntegralService.transaction(answer.getUsername(),
                user.getUsername(),answer.getAnswerMoney(),
                Const.TradingNotes.FOUR,Const.TradingNotes.FOUR);
        if(!response.isSuccess()){
            return response;
        }
        //添加用户支付记录
        AnswerPayRecord answerPayRecord = new AnswerPayRecord();
        answerPayRecord.setAnswerId(answerId);//回答Id
        answerPayRecord.setQuestionId(answer.getQid());//问题Id
        answerPayRecord.setMoney(answer.getAnswerMoney());//支付金额
        answerPayRecord.setUsername(user.getUsername());//支付用户
        answerPayRecord.setIp(ToolUtil.getClientIp(request));//IP
        if(answerPayRecordMapper.insert(answerPayRecord) <= 0){
            throw new RuntimeException();
        }
        return ServerResponse.createByErrorMessage(Const.Msg.SELECTERROR);
    }

}
